package cn.weekimwee.firstlineofcodeforkotlin.unit10.download

import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.AsyncTask.execute
import android.os.Binder
import android.os.Environment
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import cn.weekimwee.firstlineofcodeforkotlin.R
import org.jetbrains.anko.notificationManager
import org.jetbrains.anko.toast
import java.io.File

class DownloadService : Service() {

    private var downloadTask: DownloadTask? = null
    private var downloadUrl: String = ""
    private val binder = DownloadBinder()

    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    inner class DownloadBinder : Binder() {
        fun startDownload(url: String) {
            if (downloadTask == null) {
                downloadUrl = url
                downloadTask = DownloadTask().apply {
                    onProgress = { progress ->
                        notificationManager.notify(1, getNotification("downloading...", progress))
                    }
                    onSuccess = {
                        downloadTask = null
                        stopForeground(true)
                        notificationManager.notify(1, getNotification("download success", -1))
                        toast("download success")
                    }
                    onFailed = {
                        downloadTask = null
                        stopForeground(true)
                        notificationManager.notify(1,getNotification("download failed",-1))
                        toast("download failed")
                    }
                    onPaused = {
                        downloadTask = null
                        toast("paused")
                    }
                   onCanceled = {
                        downloadTask = null
                        stopForeground(true)
                        toast("canceled")
                    }
                }
            }
            downloadTask?.execute(downloadUrl)
            startForeground(1,getNotification("downloading...",0))
            toast("downloading...")
        }

        fun pauseDownload() {
            if(downloadTask!=null){
                downloadTask?.pauseDownload()
            }
        }

        fun cancelDownload(){
            if(downloadTask!=null){
                downloadTask?.cancelDownload()
            }
            val fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"))
            val dic = ((Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))).path
            val file = File(dic+fileName)
            if(file.exists())file.delete()
            notificationManager.cancel(1)
            stopForeground(true)
            toast("canceled")
        }
    }


    private fun getNotification(str: String, p: Int): Notification {
        val intent = Intent(this@DownloadService,DownloadActivity::class.java)
        val pi = PendingIntent.getActivity(this@DownloadService,0,intent,0)
        val builder = NotificationCompat.Builder(this@DownloadService)
        builder.setSmallIcon(R.mipmap.ic_launcher)
        builder.setLargeIcon(BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher))
        builder.setContentIntent(pi)
        builder.setContentTitle(str)
        if(p>=0){
            builder.setContentTitle("$p%")
            builder.setProgress(100,p,false)
        }
        return builder.build()
    }
}
